In this tutorial, we are going to learn to create a simple cookie-based visitor counter. This counter will start from zero and will be incremented for each visit.
For the sake of testing the code, the counter will reset after you close the browser.
setcookie() defines a cookie to be sent along the rest of the HTTP headers. Like other headers, cookies must be addressed before any output from your code.
A counter in PHP using Cookies
setcookie() method has the following syntax.
setcookie ( string $name [, string $value = "" [, int $expires = 0 [, string $path = "" [, string $domain = "" [, bool $secure = FALSE [, bool $httponly = FALSE ]]]]]] ) : bool
If you don’t set the time of expiry for the cookie or set it to 0, it will be expired as you close the browser.
<?php $total_count = 0; if(isset($_COOKIE['count'])){ $total_count = $_COOKIE['count']; $total_count ++; } if(isset($_COOKIE['last_visit'])){ $last_visit = $_COOKIE['last_visit']; } setcookie('count', $total_count); setcookie('last_visit', date("H:i:s")); if($total_count == 0){ echo "Welcome! We are glad to see you here."; } else { echo "This is your visit number ".$total_count; echo '<br>'; echo "Last time, you were here at ".$last_visit; } ?>
If you want to set the cookie for 24 hours, use the following lines of code
<?php setcookie('count', $total_count, time()+60*60*24); setcookie('last_visit', date("d-m-Y H:i:s"), time()+60*60*24); ?>
time() + 60*60*24 refers to 24 hours. Each hour has 60 minutes and each minute has 60 seconds.
Related Articles
Get the Number of Odd & Even Numbers in an Array using C
Populate DataTable using DataReader in VB.NET
Bind an ADO.NET DataTable to a TreeView using C#
Comments